<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 :closable="false"(是否展示“X”号) show-icon(显示图标) -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader ref="cateHandle" v-model="selectedKeys" :options="parentCateList" :props="cascaderProps" @change="parentCateChange" clearable change-on-select></el-cascader>
        </el-col>
        <el-col></el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 将标签页改为many -->
        <el-tab-pane label="动态参数" name="many">
          <el-button size="small" type="primary" :disabled="isButtonDisabled">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe row-key="attr_id">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template #default="{ row }">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, i) in row.attr_vals" :key="i" closable @close="removeAttrVal(row, i)">{{ item }}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                  v-if="row.inputVisible"
                  v-model="row.inputVal"
                  class="input-new-tag"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter="saveAttrVal(row)"
                  @blur="row.inputVisible = false"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="编号" width="80"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template #default>
                <el-button size="small" type="primary" :icon="Edit">编辑</el-button>
                <el-button size="small" type="danger" :icon="Delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button size="small" type="primary" :disabled="isButtonDisabled">添加属性</el-button>
          <el-table :data="onlyTableData" border stripe row-key="attr_id">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template #default="{ row }">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, i) in row.attr_vals" :key="i" closable @close="removeAttrVal(row, i)">{{ item }}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                  v-if="row.inputVisible"
                  v-model="row.inputVal"
                  class="input-new-tag"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter="saveAttrVal(row)"
                  @blur="row.inputVisible = false"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="编号" width="80"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template #default>
                <el-button size="small" type="primary" :icon="Edit">编辑</el-button>
                <el-button size="small" type="danger" :icon="Delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { computed, ref, nextTick } from 'vue'
import { getCateListApi } from '@/api/cate'
import { getAttrListApi, editAttrApi } from '@/api/params'
import { message } from '@/utils/functions'
// 自定义指令：如在模板中启用 v-focus实现聚焦
/* const vFocus = {
  mounted: async el => {
    await nextTick()
    el.focus()
  }
} */

// 默认激活的选项卡
const activeName = ref('many')
// 切换选项卡时触发的事件
const handleTabClick = tab => {
  activeName.value = tab.paneName
  if (cat_id.value === 0) {
    message('error', '请先选择三级分类菜单')
    return
  }
  getParamsData(cat_id.value, activeName.value)
}
// 动态参数数据
const manyTableData = ref([])

// 获取静态参数数据
const onlyTableData = ref([])
// 根据分类id和类型获取参数数据
const getParamsData = async (cat_id, type) => {
  // 获取动态参数数据
  if (type === 'many') {
    const data = await getAttrListApi(cat_id, 'many')
    // 处理数据
    data.forEach(item => {
      // attr_vals是字符串，需要转换为数组
      item.attr_vals = item.attr_vals.split(',')
      // 添加inputVisible属性，用于控制输入框的显示与隐藏
      item.inputVisible = false
      item.inputVal = ''
    })
    manyTableData.value = data
  } else {
    // 获取静态参数数据
    const data = await getAttrListApi(cat_id, 'only')
    // 处理数据
    data.forEach(item => {
      // attr_vals是字符串，需要转换为数组
      item.attr_vals = item.attr_vals.split(',')
      // 添加inputVisible属性，用于控制输入框的显示与隐藏
      item.inputVisible = false
      item.inputVal = ''
    })
    onlyTableData.value = data
  }
}

// 添加属性/添加参数的按钮的激活状态
const isButtonDisabled = computed(() => {
  return selectedKeys.value === undefined || selectedKeys.value.length !== 3
})
// 分类id
const cat_id = computed(() => {
  if (selectedKeys.value === undefined) {
    return ''
  }
  return selectedKeys.value.length ? selectedKeys.value[selectedKeys.value.length - 1] : ''
})

// 构建修改的数据
const editAttrFormData = ref({
  id: '', // 分类id
  attrId: '', // 属性id
  attr_name: '', // 属性名
  attr_sel: '', // 属性类型
  attr_vals: '' // 属性值
})

// 删除属性值
const removeAttrVal = async (row, index) => {
  // 删除选中的属性值
  row.attr_vals.splice(index, 1)
  await editAttr(row)
}
// 回车时添加属性值
const saveAttrVal = async row => {
  if (row.inputVal.trim() === '') {
    message('warning', '请输入内容')
    return
  }
  row.attr_vals.push(row.inputVal)
  await editAttr(row)
}

// 修改属性的方法
const editAttr = async row => {
  editAttrFormData.value.id = cat_id.value
  editAttrFormData.value.attrId = row.attr_id
  editAttrFormData.value.attr_name = row.attr_name
  editAttrFormData.value.attr_sel = row.attr_sel
  editAttrFormData.value.attr_vals = row.attr_vals.join(',')
  await editAttrApi(editAttrFormData.value)
  message('success', '更新成功')
  row.inputVisible = false
  row.inputValue = ''
  getParamsData(cat_id.value, activeName.value)
}

// 文本输入框dom节点
const saveTagInput = ref(null)
// 展示添加属性值的文本输入框
const showInput = async row => {
  row.inputVisible = true
  await nextTick()
  saveTagInput.value.focus()
}

// 级联菜单相关
// 分类数据
const parentCateList = ref([])
// 级联菜单选中项的值（每个下拉选项的value值的数组）
const selectedKeys = ref([])
// 配置级联菜单中数据如何展示
const cascaderProps = ref({
  // 当要展示的下拉选项的数据的属性不是value和label时，需要配置该属性
  value: 'cat_id',
  label: 'cat_name',
  // 多级的数据的关联关系字段不是children时需要配置该属性
  children: 'children',
  // 默认情况下，级联菜单的选项是点击触发的，如果需要hover触发，需要配置该属性
  expandTrigger: 'hover',
  // 设置父子节点取消选中关联，从而达到选择任意一级选项的目的
  checkStrictly: true
})

// 获取一、二级分类数据
const getparentCateList = async () => {
  const data = await getCateListApi({ type: 3 })
  parentCateList.value = data
}
getparentCateList()
// 组件对象
const cateHandle = ref(null)
const parentCateChange = () => {
  console.log(selectedKeys.value)

  if (selectedKeys.value === undefined) {
    manyTableData.value = []
    onlyTableData.value = []
    return
  }
  // 只允许选择三级分类作为参数所属的分类
  if (selectedKeys.value.length !== 3) {
    manyTableData.value = []
    onlyTableData.value = []
    selectedKeys.value = []
    // 选中了父级后，让级联菜单隐藏
    cateHandle.value.togglePopperVisible(false)
    return
  }
  // 根据当前激活的是哪个tab选项来获取参数数据
  getParamsData(cat_id.value, activeName.value)
  // 选中了父级后，让级联菜单隐藏
  cateHandle.value.togglePopperVisible(false)
}
</script>

<style lang="scss" scoped>
.cat_opt {
  margin: 20px 0;
}
.el-cascader {
  margin-left: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
  margin: 10px;
}
.button-new-tag {
  margin: 10px;
}
</style>